#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <pthread.h>
#include <unistd.h>

static const int defaultnum = 5;

struct ThreadInfo
{
    pthread_t tid;
    std::string name;
};

template <class T>
class ThreadPool
{
public:
    void Lock()
    {
        pthread_mutex_lock(&mutex_);
    }

    void Unlock()
    {
        pthread_mutex_unlock(&mutex_);
    }    
    void Wakeup()
    {
        pthread_cond_signal(&cond_);
    }
    void ThreadSleep()
    {
        pthread_cond_wait(&cond_, &mutex_);
    }

    bool QueueIsEmpty()
    {
        return tasks_.empty();
    }
    std::string GetThreadName(pthread_t tid)
    {
        for(const auto& ti : threads_)
        {
            if(ti.tid == tid) return ti.name;
        }
        return "None";
    }
public:
    static void* HandlerTask(void* args) //static修饰后不会有隐含的this指针导致参数不匹配问题
    {
        ThreadPool<T>* tp = static_cast<ThreadPool<T>*> (args);
        std::string name = tp->GetThreadName(pthread_self());
        while(true)
        {
            tp->Lock();
            while(tp->QueueIsEmpty())//没有任务就休眠
            {
                tp->ThreadSleep();
            }
            //有任务就去执行任务
            //获取任务
            T t = tp->Pop();
            tp->Unlock();

            t();//执行任务
            std::cout << name << "run , res :" << t.GetRes() << std::endl;
        }
    }

    void Start()
    {
        int num = threads_.size();
        for(int i = 0; i < num; i++)
        {
            threads_[i].name = "thread-" + std::to_string(i+1);
            pthread_create(&(threads_[i].tid),nullptr,HandlerTask,this);
        }
    }

    void Push(const T& t)
    {
        Lock();
        tasks_.push(t);
        Wakeup();
        Unlock();
    }

    T Pop()
    {
        T t = tasks_.front();
        tasks_.pop();
        return t;
    }

    static ThreadPool<T>* GetInstance()
    {
        if(tp_ == nullptr)//多一层判断避免多次申请锁的情况，导致性能下降
        {
            pthread_mutex_lock(&lock_);
            if(tp_ == nullptr)
            {
                std::cout << "Log : Sigleton create done ..." << std::endl;
                tp_ = new ThreadPool<T>();
            }
            pthread_mutex_unlock(&lock_);
        }

        return tp_;
    }
private:
    //需要将构造和析构私有
    //避免构成临时对象破坏单例
    ThreadPool(int num = defaultnum) : threads_(num)
    {
        pthread_mutex_init(&mutex_, nullptr);
        pthread_cond_init(&cond_, nullptr);
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&mutex_);
        pthread_cond_destroy(&cond_);
    }
    ThreadPool(const ThreadPool<T>&) = delete;
    const ThreadPool<T> operator=(const ThreadPool<T>&) = delete;

private:
    std::vector<ThreadInfo> threads_; // 用vector容器存放线程池
    std::queue<T> tasks_; 

    pthread_mutex_t mutex_;
    pthread_cond_t cond_;

    static ThreadPool<T> *tp_;//懒汉模式下的静态单例对象
    static pthread_mutex_t lock_;
};

//初始化
template<class T>
ThreadPool<T> *ThreadPool<T>::tp_ = nullptr;

template<class T>
pthread_mutex_t ThreadPool<T>::lock_ =PTHREAD_MUTEX_INITIALIZER;